﻿using UnityEngine;
using Jinndev.UI;
using UnityEngine.EventSystems;

namespace Jinndev {

    /// <summary>
    /// 颜色选择器层级
    /// </summary>
    public class ColorPickerLayer : BaseUIBehaviour, IEscape {

        #region static
        public static readonly string PATH = "Prefab/UI/Common/ColorPickerLayer";
        public static Vector2 LastPosition = new Vector2();

        public static ColorPickerLayer Create(System.Action<Color> onColorChanged) {
            var colorPickerLayer = UIManager.Instance.AddTop<ColorPickerLayer>(PATH);
            colorPickerLayer.onColorChanged = onColorChanged;
            return colorPickerLayer;
        }
        public static ColorPickerLayer Create(Transform container, System.Action<Color> onColorChanged) {
            var colorPickerLayer = CommonUtil.Instantiate<ColorPickerLayer>(PATH, container);
            colorPickerLayer.onColorChanged = onColorChanged;
            return colorPickerLayer;
        }
        #endregion

        public GameObject colorPickerPrefab;
        public RectTransform colorPickerSlot;
        public RectTransform panel;
        public DragHelper dragHelper;

        private FlexibleColorPicker colorPicker;

        private void Awake() {
            panel.anchoredPosition = LastPosition;
            dragHelper.onDrag += OnDrag;

            if (colorPickerPrefab == null) {
                Debug.LogError("颜色选择器预设为空");
                return;
            }
            colorPicker = CommonUtil.Instantiate<FlexibleColorPicker>(colorPickerPrefab, colorPickerSlot);
        }

        private void OnDestroy() {
            LastPosition = panel.anchoredPosition;
        }

        public System.Action<Color> onColorChanged {
            set {
                if (colorPicker != null) {
                    colorPicker.onColorChanged = value;
                }
            }
        }

        public Color color {
            get {
                return colorPicker != null ? colorPicker.color : Color.white;
            }
            set {
                if (colorPicker != null) {
                    colorPicker.color = value;
                }
            }
        }

        private void OnDrag(DragHelper helper, PointerEventData eventData, float deltaX, float deltaY) {
            panel.Translate(-deltaX, -deltaY, 0);
        }


        /// <summary>
        /// 当由UIManager托管时会截断Esc键
        /// </summary>
        public EscapeResult OnEscape() {
            return EscapeResult.Destroy;
        }

    }

}
